const express = require('express');
const { body } = require('express-validator');
const serviceController = require('../controllers/serviceController');
const { protect, restrictTo, optionalAuth } = require('../middleware/auth');
const rateLimit = require('express-rate-limit');

const router = express.Router();

// 限制服务操作请求的频率
const serviceLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 200, // 限制每个IP 15分钟内最多200次请求
  message: {
    status: 'error',
    message: '请求过于频繁，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
});

// 验证规则
const createServiceValidation = [
  body('name')
    .isLength({ min: 1, max: 100 })
    .withMessage('服务名称长度必须在1-100个字符之间'),
  
  body('category')
    .isIn(['pet_sitting', 'dog_walking', 'pet_grooming', 'pet_training', 'veterinary_care', 'pet_boarding', 'pet_transportation', 'emergency_care'])
    .withMessage('服务分类无效'),
  
  body('description.short')
    .isLength({ min: 10, max: 200 })
    .withMessage('简短描述长度必须在10-200个字符之间'),
  
  body('description.detailed')
    .isLength({ min: 50, max: 2000 })
    .withMessage('详细描述长度必须在50-2000个字符之间'),
  
  body('applicablePetTypes')
    .isArray({ min: 1 })
    .withMessage('至少需要选择一种适用的宠物类型')
    .custom((value) => {
      const validPetTypes = ['dog', 'cat', 'bird', 'fish', 'rabbit', 'hamster', 'guinea_pig', 'reptile', 'other'];
      if (!value.every(type => validPetTypes.includes(type))) {
        throw new Error('包含无效的宠物类型');
      }
      return true;
    }),
  
  body('characteristics.duration.min')
    .isInt({ min: 15, max: 1440 })
    .withMessage('最小时长必须在15-1440分钟之间'),
  
  body('characteristics.duration.max')
    .isInt({ min: 15, max: 1440 })
    .withMessage('最大时长必须在15-1440分钟之间')
    .custom((value, { req }) => {
      if (value < req.body.characteristics.duration.min) {
        throw new Error('最大时长不能小于最小时长');
      }
      return true;
    }),
  
  body('characteristics.location')
    .isIn(['home', 'caregiver_home', 'outdoor', 'clinic', 'any'])
    .withMessage('服务地点必须是 home、caregiver_home、outdoor、clinic 或 any'),
  
  body('characteristics.requiresSpecialSkills')
    .isBoolean()
    .withMessage('是否需要特殊技能必须是布尔值'),
  
  body('characteristics.isEmergencyService')
    .isBoolean()
    .withMessage('是否为紧急服务必须是布尔值'),
  
  body('characteristics.isRecurringAllowed')
    .isBoolean()
    .withMessage('是否允许重复服务必须是布尔值'),
  
  body('requiredSkills')
    .optional()
    .isArray()
    .withMessage('所需技能必须是数组'),
  
  body('requiredCertifications')
    .optional()
    .isArray()
    .withMessage('所需认证必须是数组'),
  
  body('pricing.basePrice')
    .isFloat({ min: 1, max: 10000 })
    .withMessage('基础价格必须在1-10000之间'),
  
  body('pricing.unit')
    .isIn(['hour', 'day', 'service', 'visit'])
    .withMessage('计价单位必须是 hour、day、service 或 visit'),
  
  body('pricing.currency')
    .isIn(['CNY', 'USD', 'EUR'])
    .withMessage('货币类型必须是 CNY、USD 或 EUR'),
  
  body('pricing.additionalPetMultiplier')
    .optional()
    .isFloat({ min: 0, max: 5 })
    .withMessage('额外宠物倍数必须在0-5之间'),
  
  body('pricing.emergencyMultiplier')
    .optional()
    .isFloat({ min: 1, max: 5 })
    .withMessage('紧急服务倍数必须在1-5之间'),
  
  body('serviceProcess')
    .optional()
    .isArray()
    .withMessage('服务流程必须是数组'),
  
  body('safetyGuidelines')
    .optional()
    .isArray()
    .withMessage('安全指南必须是数组'),
  
  body('qualityStandards')
    .optional()
    .isArray()
    .withMessage('质量标准必须是数组'),
  
  body('tags')
    .optional()
    .isArray()
    .withMessage('标签必须是数组'),
  
  body('searchKeywords')
    .optional()
    .isArray()
    .withMessage('搜索关键词必须是数组')
];

const updateServiceValidation = [
  body('name')
    .optional()
    .isLength({ min: 1, max: 100 })
    .withMessage('服务名称长度必须在1-100个字符之间'),
  
  body('description.short')
    .optional()
    .isLength({ min: 10, max: 200 })
    .withMessage('简短描述长度必须在10-200个字符之间'),
  
  body('description.detailed')
    .optional()
    .isLength({ min: 50, max: 2000 })
    .withMessage('详细描述长度必须在50-2000个字符之间'),
  
  body('pricing.basePrice')
    .optional()
    .isFloat({ min: 1, max: 10000 })
    .withMessage('基础价格必须在1-10000之间')
];

const priceCalculationValidation = [
  body('serviceId')
    .isMongoId()
    .withMessage('服务ID无效'),
  
  body('startDateTime')
    .isISO8601()
    .withMessage('开始时间格式无效'),
  
  body('endDateTime')
    .isISO8601()
    .withMessage('结束时间格式无效')
    .custom((value, { req }) => {
      const endDate = new Date(value);
      const startDate = new Date(req.body.startDateTime);
      if (endDate <= startDate) {
        throw new Error('结束时间必须晚于开始时间');
      }
      return true;
    }),
  
  body('petCount')
    .optional()
    .isInt({ min: 1, max: 20 })
    .withMessage('宠物数量必须在1-20之间'),
  
  body('isEmergency')
    .optional()
    .isBoolean()
    .withMessage('是否紧急服务必须是布尔值')
];

const statusValidation = [
  body('status')
    .isIn(['active', 'inactive', 'draft'])
    .withMessage('状态必须是 active、inactive 或 draft')
];

const bulkUpdateValidation = [
  body('serviceIds')
    .isArray({ min: 1 })
    .withMessage('服务ID列表不能为空')
    .custom((value) => {
      if (!value.every(id => typeof id === 'string' && id.length === 24)) {
        throw new Error('服务ID格式无效');
      }
      return true;
    }),
  
  body('updateData')
    .isObject()
    .withMessage('更新数据必须是对象')
];

// 应用限流中间件到所有路由
router.use(serviceLimiter);

// 公开路由（可选认证）

/**
 * @route   GET /api/services
 * @desc    获取所有服务
 * @access  Public
 */
router.get('/', optionalAuth, serviceController.getAllServices);

/**
 * @route   GET /api/services/search
 * @desc    搜索服务
 * @access  Public
 */
router.get('/search', optionalAuth, serviceController.searchServices);

/**
 * @route   GET /api/services/categories
 * @desc    获取服务分类
 * @access  Public
 */
router.get('/categories', optionalAuth, serviceController.getServiceCategories);

/**
 * @route   GET /api/services/popular
 * @desc    获取热门服务
 * @access  Public
 */
router.get('/popular', optionalAuth, serviceController.getPopularServices);

/**
 * @route   GET /api/services/recommended
 * @desc    获取推荐服务（登录用户可获得个性化推荐）
 * @access  Public
 */
router.get('/recommended', optionalAuth, serviceController.getRecommendedServices);

/**
 * @route   POST /api/services/calculate-price
 * @desc    计算服务价格
 * @access  Public
 */
router.post('/calculate-price', priceCalculationValidation, serviceController.calculateServicePrice);

/**
 * @route   GET /api/services/:id
 * @desc    获取单个服务
 * @access  Public
 */
router.get('/:id', optionalAuth, serviceController.getService);

/**
 * @route   GET /api/services/:id/reviews
 * @desc    获取服务评价
 * @access  Public
 */
router.get('/:id/reviews', optionalAuth, serviceController.getServiceReviews);

// 需要认证的路由
router.use(protect);

// 管理员功能

/**
 * @route   GET /api/services/admin/stats
 * @desc    获取服务统计信息
 * @access  Private/Admin
 */
router.get('/admin/stats', restrictTo('admin'), serviceController.getServiceStats);

/**
 * @route   POST /api/services/admin
 * @desc    创建新服务
 * @access  Private/Admin
 */
router.post('/admin',
  restrictTo('admin'),
  serviceController.uploadServiceImages,
  serviceController.processServiceImages,
  createServiceValidation,
  serviceController.createService
);

/**
 * @route   PATCH /api/services/admin/bulk-update
 * @desc    批量更新服务
 * @access  Private/Admin
 */
router.patch('/admin/bulk-update',
  restrictTo('admin'),
  bulkUpdateValidation,
  serviceController.bulkUpdateServices
);

/**
 * @route   PATCH /api/services/admin/:id
 * @desc    更新服务
 * @access  Private/Admin
 */
router.patch('/admin/:id',
  restrictTo('admin'),
  serviceController.uploadServiceImages,
  serviceController.processServiceImages,
  updateServiceValidation,
  serviceController.updateService
);

/**
 * @route   PATCH /api/services/admin/:id/status
 * @desc    更新服务状态
 * @access  Private/Admin
 */
router.patch('/admin/:id/status',
  restrictTo('admin'),
  statusValidation,
  serviceController.updateServiceStatus
);

/**
 * @route   DELETE /api/services/admin/:id
 * @desc    删除服务
 * @access  Private/Admin
 */
router.delete('/admin/:id', restrictTo('admin'), serviceController.deleteService);

module.exports = router;